/**
 * Created by ruiyuan on 15-9-22.
 */
'use strict';

/* App Module */

var searchApp = angular.module('searchApp', ['ngRoute', 'ngResource', 'marketFilters']);
var params = {};
var tempArray = window.location.search.split('?');
if (tempArray.length == 2) {
    var parts = tempArray[1].split('&');
    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}
//var host = 'localhost:3000';
/*var host = 't.app.66xiaoqu.com';*/
/*  宝宝树66小区二次改造    mod   dayu.wedo  20170723   start   */
var host = 'app-66xiaoqu.babytree.com';
// var host = 'app.h2oprint.com';
// var host = '192.168.2.114:3000';
// var host = 'app-66xiaoqu.babytree.com';
/*  宝宝树66小区二次改造    mod   dayu.wedo  20170723   end   */

searchApp.controller('SearchCtrl', ['$scope', 'Goods', 'SaleRecord', '$http',
    function ($scope, Goods, SaleRecord, $http) {

        var startTime = moment().startOf('week').add(6, 'day').add(18, 'hour');
        var endTime = moment().startOf('week').add(6, 'day').add(22, 'hour');

        var isMore = false;//判断是否有更多数据
        var isFinish = true;

        $scope.ts = '*';
        $scope.goodsList = [];
        $scope.keyword = '';
        $scope.goodsClaId = '';
        $scope.history = localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')).slice(0, 10) : [];
        $scope.hot = ['手机', '书', '加湿器', '空调', '相机', '童装', '鞋子', '背包', '充电器'];
        // $scope.goodsCla = ['求购','手机/数码','母婴/儿童玩具/儿童车','家居/日用品','鞋包/服饰/配饰',
        //     '电动车/自行车','卡券票务','书刊音像/文体用品','宠物用品','食品/保健品','其它闲置'];
        // $scope.historyRec = [];

        $('.loading-pop').hide();
        $('.searchInput').focus();

        $('.searchInput').on('focus', function () {
            $('.no_result').css('display', 'none');
        });

        $scope.clearHistory = function () {
            localStorage.removeItem('history');
            $scope.history = [];
            // $scope.historyRec = [];
        };


        $('.searchInput').on('search', function () {

            if ($('.searchInput').val() != '') {
                $scope.search();
            }
        });

        // 1120-commit-master
        $scope.hotSearch = function (value) {
            $('.searchInput').val(value);
            /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 start */
            // $('#goodsClaId').val("0");
            /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 end */
            $scope.search();
        };
        /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 start */
        // $scope.goodsClaSearch = function (goodsClaObj) {
        //     $('.searchInput').val(goodsClaObj.name);
        //     $('#goodsClaId').val(goodsClaObj.goodsClaId);
        //     $scope.search();
        // };

        // angular.element(document).ready(function() {
        //     // $scope.init();
        //     if ($scope.history && $scope.history.length > 0) {
        //         if ($scope.history.length > 10) {
        //             $scope.history = $scope.history.slice(0, 10);
        //         }
        //         // $scope.historyRec = [];
        //         for (var i = 0, length = $scope.history.length; i < length; i++) {
        //             var hisObj = {};
        //             hisObj.name = $scope.history[i].split("_")[0];
        //             hisObj.goodsClaId = $scope.history[i].split("_")[1];
        //             $scope.historyRec.push(hisObj);
        //         }
        //     }
        // });

        //获取闲置商品分类数据
        // $scope.init = function(){
        //     $http.get('http://' + host + '/rest/v1.0/market/goods/searchGoodsCategory/'+ params.token + '/' + params.deviceId)
        //         .then(function successCallback(data) {
        //         // alert("获取闲置商品分类成功!"+ data.data.data);
        //         if (data && data.data.data) {
        //             $scope.goodsCla = data.data.data;
        //         }
        //     },
        //     function errorCallback(data) {
        //         console.log("获取闲置商品分类失败!"+ data.result.message);
        //         // alert("获取闲置商品分类成功!"+ data.result.message);
        //     });
        // };

        // 根据闲置分类检索闲置商品
        $scope.searchGoodsByCtg = function (goodsClaId) {
            // alert("原生js调用angularjs中的方法。。。" + goodsClaId);
            var keyword = $('.searchInput').val();
            // alert("获取检索框输入的关键字。。。" + keyword);
            $scope.goodsClaId = goodsClaId;
            // $('.searchInput').val(keyword);
            // $('#goodsClaId').val($scope.goodsClaId);
            // alert("闲置分类ID同步到angular控制器中。。。" + $scope.goodsClaId);
            $scope.search();
        };

        /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 end */

        $scope.historySearch = function (value) {
            /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 start */
            // $('.searchInput').val(historyObj.name);
            // $('#goodsClaId').val(historyObj.goodsClaId);
            // alert(historyObj.name + "=====" + historyObj.goodsClaId);

            $('.searchInput').val(value);
            /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 start */
            $scope.search();
        };

        $scope.search = function () {
            $scope.ts = '*';
            isMore = false;
            $('.no_result').css('display', 'none');
            var keyword = $('.searchInput').val();
            /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 start */
            // var goodsClaId = $('#goodsClaId').val();
            if (keyword == "" && $scope.goodsClaId == "") {
                return ;
            }
            // var keywordIdHis = "";
            // // var keywordIdHis = keyword == '' ? '' : keyword + "_" + "0";
            // if (keyword != "") {
            //     keywordIdHis = keyword + "_" + "0";
            // }
            // var keywordIdHis = keyword + "_" + goodsClaId;
            // if (keywordIdHis != "") {
            //     if ($scope.history.indexOf(keywordIdHis) == -1) {
            //         $scope.history.unshift(keywordIdHis);
            //         if ($scope.history.length > 10) {
            //             $scope.history = $scope.history.slice(0, 10);
            //         }
            //         // $scope.historyRec = [];
            //         for (var i = 0, length = $scope.history.length; i < length; i++) {
            //             var hisObj = {};
            //             hisObj.name = $scope.history[i].split("_")[0];
            //             hisObj.goodsClaId = $scope.history[i].split("_")[1];
            //             $scope.historyRec.push(hisObj);
            //         }
            //         localStorage.setItem('history', JSON.stringify($scope.history));
            //     }
            // }
            if (keyword != "") {
                if ($scope.history.indexOf(keyword) == -1) {
                    $scope.history.unshift(keyword);
                    if ($scope.history.length > 10) {
                        $scope.history = $scope.history.slice(0, 10);
                    }
                    localStorage.setItem('history', JSON.stringify($scope.history));
                }
            }

            $scope.keyword = decodeURIComponent(keyword.trim());
            $scope.goodsClaId = decodeURIComponent($scope.goodsClaId.trim());
            /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 end */

            $('.searchInput').blur();
            $('.search_page').css({display: 'none'});
            $('.layout').css({display: 'block'});
            $scope.getNewData(true);
        };

        $('.searchInput').on('focus', function () {
            $('.search_page').css({display: 'block'});
            $('.layout').css({display: 'none'});
            $('.no_result').css({display: 'none'});
            // $('#goodsClaId').val("0");
        });

        /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171128 start */
        //获取数据
        $scope.getNewData = function (flag) {
            Goods.search({
                keyword: $scope.keyword,
                goodsClaId: $scope.goodsClaId,
                ts: $scope.ts
            }, function (result) {
                $scope.goodsClaId = '';
                if (result != null && result.data != null && result.data.list.length > 0) {
                    if (flag) {
                        $scope.goodsList = result.data.list;
                    } else {
                        $scope.goodsList = $scope.goodsList.concat(result.data.list);
                    }

                    $scope.ts = result.data.ts;
                    isMore = result.data.list.length > 0;
                }
                // 用户过期，跳转到登录页面重新登录--调用客户端的方法
                // if (result.result.status == '101') {
                //     loginAgainAction();
                // }

                if ($scope.ts == '*') {
                    if (result.data == null || result.data.list.length == 0) {
                        $('.layout').css('display', 'none');
                        $('.no_result').css('display', 'block');
                    }
                }
                isFinish = true;
                $(".loadingMore").html('');

                // if (result.data != null && result.data.list.length == 0 && $scope.ts == '*') {
                //     $('.no_result').css('display', 'block');
                // }
            });
        };
        /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171128 end */

        //去二手详情
        $scope.goToDetail = function (goods) {

            if ((!moment().isBetween(startTime, endTime)) && goods.saleNumber != null) {
                $('#saleRecordMsg').text(goods.isRecord ? '已标注' : '到时通知我');
                $('#reged').css('display', 'block');
                $scope.goods = goods;
            } else {
                window.location.href = "detail.html" + window.location.search + '&goodsId=' + goods.objId + '&createdBy=' + goods.createdBy + '&clickSource=702';
            }
        };

        //2、滚动加载更多
        $('.wrapper').scroll(function () {
            if (isMore && isFinish) {
                var contentHeight = $(".wrapper")[0].scrollHeight;
                var h = $(".wrapper").height();

                if ((contentHeight - h - $(this).scrollTop()) <= 75) {
                    isFinish = false;
                    $(".loadingMore").html('<img src="images/loading.gif" />正在加载');
                    //此处为加载下一条的方法
                    $scope.getNewData(false);
                }
            }
        }).scroll();

        // $scope.goodsImgW = (($(window).width() * 0.5) - 5) + 'px';
        // $scope.goodsImgH = (($(window).width() * 0.5) - 5) / 1.2 + 'px';
        $scope.goodsImgW = ($(window).width() - 5) * 0.5 + 'px';
        $scope.goodsImgH = (($(window).width() - 5) * 0.5 / 1.28) + 'px';

        $scope.hideSale = function () {
            document.getElementById('reged').style.display = 'none';
        };

        $scope.saveRecord = function () {
            if ($scope.goods != null && !$scope.goods.isRecord) {
                SaleRecord.save({}, {goodsId: $scope.goods.objId, goodsTitle: $scope.goods.title});
                $scope.goods.isRecord = true;
            }
            $scope.hideSale();
        };
    }
]);

/* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171128 start */
searchApp.factory('Goods', ['$resource',
    function ($resource) {
        // return $resource('http://' + host + '/rest/v1.0/market/goods/search/:keyword/:goodsClaId/:ts/' + params.token + '/' + params.deviceId, {},
        return $resource('http://' + host + '/rest/v1.0/market/goods/search/' + params.token + '/' + params.deviceId, {},
            {
                search: {
                    method: 'POST',
                    timeout: 10000
                }
            }
        )
    }
]);
/* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171128 end */

searchApp.factory('SaleRecord', ['$resource', function ($resource) {
    return $resource('http://' + host + '/rest/v1.0/market/saleRecord/' + params.token + '/' + params.deviceId, {})
}]);

/* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171128 start */
// ios/android 客户端调用原生js方法
var searchGoodsByCla = function (goodsClaId) {
    var $scope = angular.element(document.querySelector('[ng-controller = SearchCtrl]')).scope();
    // 原生js调用angularjs中的方法
    $scope.searchGoodsByCtg(goodsClaId);
    // angular.element(document.getElementById('searchApp')).scope().searchGoodsByCtg(goodsClaId);
    // searchGoods(goodsClaId);
};
/* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171128 end */
